Python Summarized
by John Liter

Python Expressions

Python expressions are pieces of code that produce a value when executed. They can include various elements such as literals, variables, operators, and function calls.

  1. Literals: Represent fixed values in code, like numbers or strings.
  2. Variables: Symbols that store values and can be used in expressions.
  3. Operators: Symbols or keywords that perform operations on operands. Examples include arithmetic operators (+, -, *, /), comparison operators (==, !=, <, >), and logical operators (and, or, not).
  4. Functions: Invoking built-in or user-defined functions can be part of an expression.
  5. Combination: Expressions can combine multiple elements to perform complex computations.

Example:

result = (3 + 5) * (2 - 7) / 4

Conditional Statements

  1. if Statement: It is used to execute a block of code only if a specified condition is true.
    if condition: # code to be executed if the condition is true
  2. else Statement: It is used in conjunction with an if statement to execute a block of code if the condition in the if statement is false.
    if condition:
        # code to be executed if the condition is true
    else:
        # code to be executed if the condition is false
  3. elif Statement: Short for "else if," it allows you to check multiple conditions in sequence.
    if condition1:
        # code to be executed if condition1 is true
    elif condition2:
        # code to be executed if condition2 is true
    else:
        # code to be executed if no conditions are true
  4. Nested Conditionals: Conditional statements can be nested inside each other to handle more complex scenarios.
    if condition1:
        if condition2:
            # code to be executed if both condition1 and condition2 are true

Functions

  1. Defining a Function: Functions are defined using the def keyword, followed by the function name and a pair of parentheses. Any input parameters are specified within the parentheses.
    def my_function(parameter1, parameter2):
        # code to be executed
  2. Calling a Function: To execute a function and utilize its functionality, you call it by using its name followed by parentheses. Input values, if any, are passed as arguments.
    result = my_function(value1, value2)
  3. Return Statement: Functions can return a value using the return statement. The returned value can be assigned to a variable or used in other parts of the code.
    def add_numbers(a, b):
        return a + b
  4. Parameters and Arguments: Parameters are variables used in the function definition, while arguments are the values passed to the function when it is called.
    def greet(name):
        print("Hello, " + name + "!")
                
    greet("Alice")
  5. Default Parameters: Function parameters can have default values, which are used if the corresponding argument is not provided during the function call.
    def power(base, exponent=2):
        return base ** exponent
  6. Scope: Variables defined inside a function have local scope, meaning they are only accessible within that function. Variables defined outside functions have global scope.

  7. Docstrings: It's a good practice to include docstrings (triple-quoted strings) in functions to document their purpose, parameters, and return values.
    def square(num):
        """Return the square of a number."""
        return num ** 2

Loops and Iterations

  1. for Loop: It iterates over a sequence (such as a list, tuple, or string) or other iterable objects. The loop continues until the sequence is exhausted.
    for element in sequence:
        # code to be executed for each element
  2. while Loop: It repeatedly executes a block of code as long as a specified condition is true.
    while condition:
        # code to be executed while the condition is true
  3. range() Function: It is often used with for loops to generate a sequence of numbers. The range() function creates a range object that represents a sequence of numbers.
    for i in range(5):
        # code to be executed for each value of i (0 to 4)
  4. break Statement: It is used to exit a loop prematurely if a certain condition is met.
    for element in sequence:
        if condition:
            break
  5. continue Statement: It skips the rest of the code inside a loop for the current iteration and moves to the next iteration.
     for element in sequence:
        if condition:
            continue
        # code here will be skipped for the current iteration if the condition is true
  6. Nested Loops: Loops can be nested inside each other, allowing for more complex iteration patterns.
    for i in range(3):
        for j in range(2):
            # code to be executed for each combination of i and j

Definite Loops

  1. for Loop: The "for" loop iterates over a sequence of elements, and the loop continues until the sequence is exhausted. It is often used when the number of iterations is predetermined.
    for element in sequence:
        # code to be executed for each element in the sequence
  2. range() Function: The "range()" function generates a sequence of numbers that can be used with a "for" loop. It is commonly employed for loops with a specific range of iterations.
    for i in range(start, stop, step):
        # code to be executed for each value of i within the specified range
    • `start`: The starting value of the sequence (default is 0).
    • `stop`: The end value (exclusive) of the sequence.
    • `step`: The step size between values (default is 1).

Finding the Largest Value

  1. Using `max()` function: This approach directly returns the maximum value in the given sequence.
    numbers = [10, 5, 8, 20, 15]
    max_value = max(numbers)
    print("The largest value is:", max_value)
  2. Manual iteration: In this approach, we iterate through the elements and update the max_value variable whenever a larger value is found.
    numbers = [10, 5, 8, 20, 15]
    max_value = numbers[0]  # Assume the first element is the largest initially
    
    for num in numbers:
        if num > max_value:
            max_value = num
    
    print("The largest value is:", max_value)

Loop Idioms

  1. Looping through a Range: Using the range() function to iterate a specific number of times.
    for i in range(n):
        # code to be executed n times
  2. Looping through Enumerated Elements: Using enumerate() to iterate through both the index and value of elements in a sequence.
    for i, element in enumerate(sequence):
        # code to be executed for each index-value pair
  3. Looping Backwards: Using a reversed range to iterate through a sequence in reverse.
    for i in range(len(sequence)-1, -1, -1):
        # code to be executed for each index in reverse order
  4. Looping through Multiple Lists: Using zip() to iterate through multiple lists simultaneously.
    for item1, item2 in zip(list1, list2):
        # code to be executed for corresponding elements of both lists
  5. List Comprehensions: A concise way to create lists or perform operations on elements that meet a certain condition.
    result = [expression for element in sequence if condition]
  6. Filtering Elements: Using list comprehensions to create a new list with elements that satisfy a specific condition.
    filtered_list = [element for element in sequence if condition]
  7. Looping until a Condition is Met: Using a while loop to repeatedly execute code until a certain condition is met.
    while not condition:
        # code to be executed until the condition is true